<template>
<el-row :gutter="20">
	<el-col :span="18">
		<el-table :data="tableData" style="width: 100%" ref="cmy">
			<el-table-column prop="id" label="编号" v-if="false"/>
			<el-table-column prop="identity" label="权限">
				<template #default="scope">
					<el-button size="small" type="primary" @click="modify_permissions(scope.row)">查看权限</el-button>
				</template>
			</el-table-column>
			修改权限
			<el-table-column prop="username" label="用户名"/>
			<el-table-column prop="password" label="密码"/>
			<el-table-column prop="creator" label="创建人"/>
			<el-table-column prop="creation_date" label="修改日期"/>
			<el-table-column align="right" width="200px">
				<template #header>
					<!-- 把按钮大小调小，否则一排放不下 -->
					<el-button size="small" @click="handleAdd()">添加角色</el-button>
					<el-button size="small" @click="refresh()">刷新表格</el-button>
				</template>
				<template #default="scope">
					<el-button size="small" @click="handleEdit(scope.row)">修改</el-button>
					<el-button
						size="small"
						type="danger"
						@click="handleDelete(scope.row)"
					>删除
					</el-button>
				</template>
			</el-table-column>
		</el-table>
	</el-col>
	<el-col :span="6">

		<el-form :inline="true">
			<el-form-item label="当前角色">
				<el-input size="small" v-model="user_permissions.username" disabled/>
			</el-form-item>
			<el-form-item>
				<el-button size="small" type="primary" @click="submit_permissions()">修改权限</el-button>
			</el-form-item>
		</el-form>

		<el-tree
			:data="data"
			show-checkbox
			node-key="id"
			:default-expanded-keys="['0','1','2','3','4']"
			:default-checked-keys="[]"
			:props="defaultProps"
			:highlight-current="true"
			ref="permissions_tree"
		/>

	</el-col>
</el-row>

<!-- 添加 / 修改角色的添加框 -->
<el-dialog v-model="dialogFormVisible" :title=" add_revise " label-width="70px">
	<el-form :model="formInline" :rules="rules" ref="form">

		<el-form-item prop="username" label="用户名">
			<el-input v-model="formInline.username" autocomplete="off"/>
		</el-form-item>

		<el-form-item prop="password" label="密码">
			<el-input v-model="formInline.password" autocomplete="off"/>
		</el-form-item>

	</el-form>
	<template #footer>
      <span class="dialog-footer">
				<!-- form?.resetFields() 关闭表单之后重置校验结果 -->
        <el-button @click="dialogFormVisible = false; form?.resetFields()">取消</el-button>
        <el-button type="primary" @click="onSubmit()">
          保存
        </el-button>
      </span>
	</template>
</el-dialog>
</template>

<script lang="ts">
export default {
	name: "PersonnelManagement"
}
</script>
<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue'
// import {useRouter} from 'vue-router'
import {ElMessage, ElMessageBox, ElTable, ElTree} from "element-plus";
import {useStore} from '@/pinia'
import type {FormInstance, FormRules} from 'element-plus'
// import {Router} from "vue-router";
import type {
	AddUserInfoResponse,
	UpdateUserInfoResponse,
	DeleteUserInfoResponse,
	UserInfoListResponse,
	UserInfo,
} from "@/api/manage/personnelManagement/type.ts"
import {
	reqAddUser,
	reqDeleteUser,
	reqUpdatePermission,
	reqUpdateUser,
	reqUserList
} from "@/api/manage/personnelManagement/index.ts";
import {UpdatePermissionsResponse} from "@/api/manage/personnelManagement/type.ts";
const store = useStore()
// const router: Router = useRouter()

// 右侧权限栏操作

// 变量存储
const user_permissions = reactive<{
	identity: string[],
	username: string,
	id: number | undefined,
}>({
	identity: [],
	username: '',
	id: undefined,
})
// 点击按钮后将权限信息传递到右侧权限栏中
const modify_permissions = (row: UserInfo) => {
	user_permissions.identity = row.identity
	user_permissions.username = row.username
	user_permissions.id = row.id
	permissions_tree.value?.setCheckedKeys(user_permissions.identity, false)
}

// 树型权限表格ref
const permissions_tree = ref<InstanceType<typeof ElTree>>()
// 提交权限变更信息
const submit_permissions = () => {
	let temp = permissions_tree.value?.getCheckedKeys(true) as string[]
	reqUpdatePermission({
		creator: store.username,
		identity: temp,
		id: user_permissions.id as number,
	}).then((result: UpdatePermissionsResponse) => {
		tableData.value = result.data
		ElMessage.success(result.success?.message)
	})
}


// 表格数据绑定
const tableData = ref<UserInfo[]>([])
// 修改用户信息
const handleEdit = (row: UserInfo) => {
	dialogFormVisible.value = true
	add_revise.value = '修改用户信息'
	formInline.username = row.username
	formInline.password = row.password
	formInline.id = row.id
	dialogFormModel = 'modify'
}

// 添加用户
const handleAdd = () => {
	dialogFormVisible.value = true
	add_revise.value = '添加用户信息'
	formInline.username = ''
	formInline.password = ''
	dialogFormModel = 'add'
}


// 在页面加载完成之后导入数据
onMounted(() => {
	reqUserList().then((result: UserInfoListResponse) => {
		tableData.value = result.data
		ElMessage.success(result.success?.message)
	})
})

// 刷新表格
const refresh = async () => {
	reqUserList().then((result: UserInfoListResponse) => {
		tableData.value = result.data
		ElMessage.success(result.success?.message)
	})
}


// 添加角色

// 表单对象
const form = ref<FormInstance>()
// 决定这个框到底是 修改框还是添加框
let dialogFormModel: string = ''
// 决定 修改/添加角色框 是否显示
const dialogFormVisible = ref<boolean>(false)
const add_revise = ref<string>('')

// 表单内容
const formInline = reactive({
	username: '',
	password: '',
	id: 0,
})
// 表单字段验证
const rules = reactive<FormRules>({
	username: [{
		required: true,
		message: '必填项',
		type: 'string',
		max: 10,
		min: 1
	}],
	password: [{
		required: true,
		message: '必填项',
		type: 'string',
		max: 10,
		min: 1
	}],
	identity: [{
		required: true,
		message: '必填项',
		type: 'string',
		max: 4,
		min: 4
	}],
})

// 提交
const onSubmit = () => {
	// 这是组件要求的，要改这个可见状态
	dialogFormVisible.value = false

	form.value?.validate(async (validate) => {
		// 添加用户信息
		if (dialogFormModel === 'add') {

			if (validate) {
				const result: AddUserInfoResponse = await reqAddUser({
					username: formInline.username.trim(),
					password: formInline.password.trim(),
					creator: store.username
				})
				tableData.value = result.data
				ElMessage.success(result.success?.message)
			}

		} else {
			// 修改用户信息
			if (validate) {
				const result: UpdateUserInfoResponse = await reqUpdateUser({
					username: formInline.username.trim(),
					password: formInline.password.trim(),
					creator: store.username,
					id: formInline.id,
				})
				tableData.value = result.data
				ElMessage.success(result.success?.message)
			}
		}
	})
}


// 删除用户
const handleDelete = (row: UserInfo) => {
	ElMessageBox.alert('确认删除本条记录吗？', '确认', {
		confirmButtonText: '确认',
		callback: async (action: any) => {
			if (action === 'confirm') {
				const result: DeleteUserInfoResponse = await reqDeleteUser({
					id: row.id,
					username: row.username,
				})
				tableData.value = result.data
				ElMessage.success(result.success?.message)
			}
		},
	})
}


const defaultProps = {
	children: 'children',
	label: 'label',
}
const data = [
	{
		id: '0',
		label: '全部权限',
		children: [

			{
				id: '1',
				label: '库存应用',
				children: [
					{
						id: 'Export',
						label: '导出记录',
					},
					{
						id: 'MaterialGroup',
						label: '物料分组',
					},
					{
						id: 'Material',
						label: '物料',
					},
					{
						id: 'HandleGroup',
						label: '处理方分组',
					},
					{
						id: 'Handle',
						label: '处理方',
					},
					{
						id: 'Record',
						label: '出入库记录',
					},
          {
            id: 'InOut',
            label: '出入库',
          },
				],
			},
			{
				id: '3',
				label: '管理应用',
				children: [
					{
						id: 'PersonnelManagement',
						label: '权限管理',
					},
				],
			},
		]
	}
]


</script>

<style scoped>

</style>